package com.xh.one2one.base.service.impl;

import com.xh.bussiness.resource.model.Material;
import com.xh.bussiness.resource.service.IMaterialService;
import com.xh.bussiness.tiku.bean.dto.KnowledgeDto;
import com.xh.bussiness.tiku.bean.dto.QuestionDto;
import com.xh.bussiness.tiku.model.Knowledge;
import com.xh.bussiness.tiku.service.IQuestionService;
import com.xh.core.util.DateUtils;
import com.xh.core.util.UserUtils;
import com.xh.one2one.base.bean.dto.StageReportDto;
import com.xh.one2one.base.bean.request.StageReportRequest;
import com.xh.one2one.base.model.OneSchool;
import com.xh.one2one.base.model.StageReport;
import com.xh.one2one.base.dao.StageReportMapper;
import com.xh.one2one.base.service.IStageReportService;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.one2one.lesson.bean.dto.LessonSummaryTimeDto;
import com.xh.one2one.lesson.bean.dto.LessonTimesDto;
import com.xh.one2one.lesson.bean.request.LessonSummaryDetailsRequest;
import com.xh.one2one.lesson.model.LessonInfo;
import com.xh.one2one.lesson.model.LessonSummary;
import com.xh.one2one.lesson.model.LessonSummaryDetails;
import com.xh.one2one.lesson.model.LessonTimes;
import com.xh.one2one.lesson.service.ILessonInfoService;
import com.xh.one2one.lesson.service.ILessonSummaryDetailsService;
import com.xh.one2one.lesson.service.ILessonSummaryService;
import com.xh.one2one.lesson.service.ILessonTimesService;
import com.xh.one2one.teachHandout.bean.request.TeachTimesHandoutRelationRequest;
import com.xh.one2one.teachHandout.model.TeachTimesHandoutRelation;
import com.xh.one2one.teachHandout.service.ITeachTimesHandoutRelationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.core.bean.XhPage;
import com.xh.core.util.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 阶段报告 服务实现类
 * </p>
 *
 * @author TW
 * @since 2021-05-20
 */
@Service
public class StageReportServiceImpl extends BaseServiceImpl<StageReportMapper, StageReport> implements IStageReportService {
    @Autowired
    private ILessonSummaryService lessonSummaryService;
    @Autowired
    private ILessonSummaryDetailsService lessonSummaryDetailsService;
    @Autowired
    private ILessonInfoService lessonInfoService;
    @Autowired
    private ILessonTimesService lessonTimesService;
    @Autowired
    private ITeachTimesHandoutRelationService teachTimesHandoutRelationService;
    @Autowired
    private IMaterialService materialService;
    @Autowired
    private IQuestionService questionService;

    @Override
    public XhPage queryStageReportPage(XhPage page, StageReportRequest bean) {
        QueryWrapper qw=new QueryWrapper<StageReport>();
        //拼装条件
        qw=prepareParams(bean, qw);

        return (XhPage) this.dao.selectPage(page,qw);
    }

    @Override
    public List queryStageReport(StageReportRequest bean) {
        bean.setCreatorId(UserUtils.getCurrentUserId());
        QueryWrapper qw=new QueryWrapper<StageReport>();
        //拼装条件
        qw=prepareParams(bean, qw);
        qw.orderByDesc("create_time");
        return this.dao.selectList(qw);
    }

    @Override
    public String createReport(StageReportRequest bean) {
        QueryWrapper qw=new QueryWrapper<StageReport>();
        qw=prepareParams(bean, qw);
        Integer count = this.dao.selectCount(qw);
        if(null == count){
            count = 0;
        }
        String  reportName = bean.getStudentName() + "第" + (count+1) + "次阶段报告";

        //查询教学总结
        QueryWrapper lessonSummaryQueryWrapper=new QueryWrapper<LessonSummary>();
        lessonSummaryQueryWrapper.eq("student_id",bean.getStudentId());
        lessonSummaryQueryWrapper.in("lesson_id",bean.getLessonIds());
        lessonSummaryQueryWrapper.orderByAsc("create_time");
        List<LessonSummary> list = lessonSummaryService.queryByCondition(lessonSummaryQueryWrapper);
        List<String> lessonIds = list.stream().map(LessonSummary::getLessonId).collect(Collectors.toList());
        String lessonIdsStr = String.join(",", lessonIds);

        StageReport report = new StageReport();
        report.setLessonId(lessonIdsStr);
        report.setStudentId(bean.getStudentId());
        report.setStudentName(bean.getStudentName());
        report.setReportName(reportName);
        this.insert(report);
        return report.getId();
    }

    @Override
    public StageReportDto queryById(String id){
        StageReportRequest reportRequest = new StageReportRequest();
        reportRequest.setId(id);
        return query(reportRequest);
    }

    @Override
    public StageReportDto query(StageReportRequest bean){

        StageReportDto dto = new StageReportDto();
        StageReport report = this.dao.selectById(bean.getId());
        String studentId = report.getStudentId();
        String[] lessonIds = report.getLessonId().split(",");
        //查询教学总结
        QueryWrapper lessonSummaryQueryWrapper=new QueryWrapper<LessonSummary>();
        lessonSummaryQueryWrapper.eq("student_id",studentId);
        lessonSummaryQueryWrapper.in("lesson_id",lessonIds);
        lessonSummaryQueryWrapper.orderByAsc("create_time");
        List<LessonSummary> list = lessonSummaryService.queryByCondition(lessonSummaryQueryWrapper);
        if(CollectionUtils.isEmpty(list)){
           return dto;
        }

        BeanUtils.copyProperties(report,dto);
        //查询讲义名称
        Map<String, LessonSummaryTimeDto> materialMap = setLessonInfo(list);

        Integer entranceScore = 0;
        Integer practiceScore = 0;
        Integer lastHomeworkScore = 0;
        List<LessonSummaryTimeDto> lessonSummaryDtos = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            LessonSummary summary = list.get(i);
            LessonSummaryTimeDto lessonSummaryDto = new LessonSummaryTimeDto();
            BeanUtils.copyProperties(summary,lessonSummaryDto);
            entranceScore += null ==summary.getEntranceScore()?0:summary.getEntranceScore();
            practiceScore += null ==summary.getPracticeScore()?0:summary.getPracticeScore();
            lastHomeworkScore += null ==summary.getLastHomeworkScore()?0:summary.getLastHomeworkScore();

            LessonSummaryTimeDto timeDto = materialMap.get(summary.getLessonId());
            lessonSummaryDto.setHandoutId(timeDto.getHandoutId());
            lessonSummaryDto.setHandoutName(timeDto.getHandoutName());
            lessonSummaryDto.setClassTime(timeDto.getClassTime());
            lessonSummaryDtos.add(lessonSummaryDto);
        }
        dto.setLessonSummaryList(lessonSummaryDtos);
        //平均分
        dto.setAvgEntranceScore(entranceScore/list.size());
        dto.setAvgPracticeScore(practiceScore/list.size());
        dto.setAvgHomeworkScore(lastHomeworkScore/list.size());

        //查询掌握情况
        Map<String, List> masterAndUnMast = getMasterAndUnMast(studentId, list);
        dto.setMaster(masterAndUnMast.get("master"));
        dto.setUnmaster(masterAndUnMast.get("unmaster"));
        //学情统计
        setStudentSituation(dto, list);
        return dto;
    }

    @Override
    public StageReport queryNew(StageReportRequest bean) {
        QueryWrapper qw=new QueryWrapper<StageReport>();
        //拼装条件
        qw=prepareParams(bean, qw);
        qw.orderByDesc("create_time");
        return this.selectFirst(qw);
    }

    public void setStudentSituation(StageReportDto dto, List<LessonSummary> list) {
        Map<Integer, List<LessonSummary>> collectAttend = list.stream().filter(data->null !=data.getAttendance()).collect(Collectors.groupingBy(LessonSummary::getAttendance));
        Map<Integer, List<LessonSummary>> collectListen = list.stream().filter(data->null !=data.getListenState()).collect(Collectors.groupingBy(LessonSummary::getListenState));
        Map<Integer, List<LessonSummary>> collectHomework = list.stream().filter(data->null !=data.getLastHomework()).collect(Collectors.groupingBy(LessonSummary::getLastHomework));
        Map<Integer, List<LessonSummary>> collectOut = list.stream().filter(data->null !=data.getOutState()).collect(Collectors.groupingBy(LessonSummary::getOutState));


        List<Integer> attend = new ArrayList<>();
        attend.add(null == collectAttend.get(1)?0:collectAttend.get(1).size());
        attend.add(null == collectAttend.get(2)?0:collectAttend.get(2).size());
        attend.add(null == collectAttend.get(3)?0:collectAttend.get(3).size());
        attend.add(null == collectAttend.get(4)?0:collectAttend.get(4).size());
        List<Integer> listen = new ArrayList<>();
        listen.add(null == collectListen.get(1)?0:collectListen.get(1).size());
        listen.add(null == collectListen.get(2)?0:collectListen.get(2).size());
        listen.add(null == collectListen.get(3)?0:collectListen.get(3).size());
        List<Integer> homework = new ArrayList<>();
        homework.add(null == collectHomework.get(1)?0:collectHomework.get(1).size());
        homework.add(null == collectHomework.get(2)?0:collectHomework.get(2).size());
        homework.add(null == collectHomework.get(3)?0:collectHomework.get(3).size());
        List<Integer> out = new ArrayList<>();
        out.add(null == collectOut.get(1)?0:collectOut.get(1).size());
        out.add(null == collectOut.get(2)?0:collectOut.get(2).size());
        out.add(null == collectOut.get(3)?0:collectOut.get(3).size());

        dto.setAttendanceList(attend);
        dto.setListenStateList(listen);
        dto.setHomeworkList(homework);
        dto.setOutStateList(out);
    }


    public Map<String,LessonSummaryTimeDto> setLessonInfo( List<LessonSummary> list){
        Map<String,LessonSummaryTimeDto> ret = new HashMap<>();
        List<String> ids = list.stream().map(LessonSummary::getLessonId).collect(Collectors.toList());
        QueryWrapper<LessonInfo> lessonInfoQueryWrapper = new QueryWrapper<>();
        lessonInfoQueryWrapper.in("id",ids);
        lessonInfoQueryWrapper.orderByAsc("create_time");
        List<LessonInfo> lessonInfos = lessonInfoService.queryByCondition(lessonInfoQueryWrapper);
        for (int i = 0; i < lessonInfos.size(); i++) {
            LessonSummaryTimeDto dto = new LessonSummaryTimeDto();
            LessonInfo lessonInfo = lessonInfos.get(i);
            String startStr = DateUtils.format(lessonInfo.getStartTime(), "yyyy-MM-dd HH:mm");
            String endStr = DateUtils.format(lessonInfo.getEndTime(), "yyyy-MM-dd HH:mm");
            String classTime = startStr +" -"+ endStr.substring(10);
            dto.setClassTime(classTime);
            String infoId = lessonInfo.getId();
            String thirdId = lessonInfo.getThirdId();
            String lessonId = lessonInfo.getLessonId();
            if(1 == lessonInfo.getType()){
                lessonId = lessonInfo.getContractId();
            }
            setHandout(dto, infoId, thirdId, lessonId);
            ret.put(infoId,dto);
        }
        return ret;
    }

    private void setHandout(LessonSummaryTimeDto dto, String infoId, String thirdId, String lessonId) {
        QueryWrapper qw=new QueryWrapper<LessonTimes>();
        qw.eq("lesson_id",lessonId);
        qw.eq("lesson_third_id",thirdId);
        LessonTimesDto lessonTimesDto = lessonTimesService.selectFirst(qw, LessonTimesDto.class);
        TeachTimesHandoutRelationRequest relationRequest = new TeachTimesHandoutRelationRequest();
        List<TeachTimesHandoutRelation> timesHandoutRelation = null;
        if(null != lessonTimesDto){
            String id = lessonTimesDto.getId();
            relationRequest.setIndexId(id);
            timesHandoutRelation = teachTimesHandoutRelationService.queryList(relationRequest);

        }
        if(CollectionUtils.isEmpty(timesHandoutRelation)){
            relationRequest.setIndexId(infoId);
            timesHandoutRelation = teachTimesHandoutRelationService.queryList(relationRequest);
        }
        if (!CollectionUtils.isEmpty(timesHandoutRelation)){
           String handoutId = timesHandoutRelation.get(0).getHandoutId();
           Material material = materialService.queryMaterialById(handoutId);
           dto.setHandoutId(material.getId());
           dto.setHandoutName(material.getFileName());
        }
    }


    public Map<String, List> getMasterAndUnMast(String studentId, List<LessonSummary> list){
        Map<String,List> ret = new HashMap<>();
        LessonSummaryDetailsRequest bean = new LessonSummaryDetailsRequest();
        bean.setStudentId(studentId);
        bean.setLessonThirdIds(list.stream().map(LessonSummary::getLessonThirdId).collect(Collectors.toList()));
        List<LessonSummaryDetails> summaryDetails = lessonSummaryDetailsService.queryLessonSummaryDetails(bean);
        if(CollectionUtils.isEmpty(summaryDetails)){
            ret.put("master",Collections.emptyList());
            ret.put("unmaster",Collections.emptyList());
        }else {
            List rigthList = new ArrayList<>();
            List wrongList = new ArrayList<>();
            summaryDetails.forEach(summary->{
                Integer correct = summary.getCorrect();
                String questionId = summary.getQuestionId();
                if(0 == correct){
                    QuestionDto question = questionService.getQuestion(questionId, null, false, true, false, false, false);
                    if(null != question){
                        if(null != question.getKnowledges()){
                            rigthList.addAll(question.getKnowledges());
                        }
                    }

                }
                if(1 == correct){
                    QuestionDto question = questionService.getQuestion(questionId, null, false, true, false, false, false);
                    if(null != question){
                        if(null != question.getKnowledges()){
                            wrongList.addAll(question.getKnowledges());
                        }
                    }

                }
            });
            boolean wrongEmpty = CollectionUtils.isEmpty(wrongList);
            boolean rightEmpty = CollectionUtils.isEmpty(rigthList);
            if(rightEmpty){
                ret.put("master",Collections.emptyList());
            }else{
                ret.put("master", rigthList);
            }
            if(wrongEmpty){
                ret.put("unmaster",Collections.emptyList());
            }else{
                ret.put("unmaster", wrongList);
            }
        }
        return ret;
    }
    /**
     * 准备条件
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(StageReportRequest bean, QueryWrapper qw) {
        if(bean.getIds()!=null&&bean.getIds().length>0){
            qw.in("id",bean.getIds());
        }
        if(StringUtils.isNotEmpty(bean.getId())){
            qw.eq("id",bean.getId());
        }
        if(StringUtils.isNotEmpty(bean.getStudentId())){
            qw.eq("student_id",bean.getStudentId());
        }
        return qw;
    }
}
